import {cartList,deleteCart,checkCart} from '@/API/index'
export default {
    namespaced:true,  //启动vuex模板
    state:{
        Cart_List:[]
    },
    actions:{
        // 获取购物车商品
       async cart_list({commit}){
            let list = await cartList();
            if (list.data.code == 200) {
                commit('CARTLIST',list.data.data)
            }
        },
        //删除商品
        async delete_cart({ commit },skuid){
            let deleteC =  await deleteCart(skuid);
            if (deleteC.data.code==200) {
                return 'OK'
            }else{
                return Promise.reject(new Error('faile'))
            }
        },
        // 获取点击的checked
        async checkcart({commit},isChecked){
            let cart = await checkCart(isChecked.skuID,isChecked.isChecked);
            if (cart.data.code==200) {
                return 'OK'
            }else{
                return Promise.reject(new Error('faile'))
            }
        },
        // 删除所有的选中商品
       alldeletecart({dispatch,state}){
           let array = []
           state.Cart_List.forEach(list => {
            list.cartInfoList.forEach( element => {
                if (element.isChecked == 1) {
                        let delete_list = dispatch('delete_cart',element.skuId);
                        array.push(delete_list);
                }
            });
         })
            return Promise.all(array);
        },
         // 选择全部选中与不选中
        AllCheckbox({dispatch,state},checked){
            let array = []
            state.Cart_List.forEach((list)=>{
                list.cartInfoList.forEach( (item)=>{
                        let cart =  dispatch('checkcart',{skuID:item.skuId,isChecked:checked})
                        array.push(cart);
                });
            })
            return Promise.all(array)
        }
    },
    mutations:{
        CARTLIST(store,list){
            store.Cart_List = list
        }
    },
    getters:{
        Cart_List(store){
            return store.Cart_List || []
        }
    }
}